"use strict";

$(document).ready(function () {
    getTopLink();
    checkloginBnet();
});
var unick;
var domain = "jdl.cn";
var loginUrl = "//sso." + domain + "/sso/login?ReturnUrl=" + encodeURIComponent(window.location.href);

/**
 * 顶部导航 View
 */
function topLinkView(topLinks) {
    return topLinks.map(function(o) {
        return "<li><a href=\""
            .concat(o.link, "\" target=\"_blank\" clstag=\"pageclick|keycount|")
            .concat(o.clstag, "\">")
            .concat(o.name, "</a></li>");
    });
}

/**
 * 顶部用户 View
 * @param {string} unick
 */
function userLinkView(unick) {
    var logined = "<li><span>您好：<a href=\"javascript:goOrer();\">"
        .concat(unick, "</a></span><i class=\"i-userPhoto\"></i></li><li><a href=\"javascript:logout();\" class=\"logout\">注销登录</a></li>");
    var unlogin = "<li><a href='\" + loginUrl + \"' class=\"btn-login\"><i class=\"i-user\"></i>请登录</a></li>";
    return unick ? logined : unlogin;
  }

/**
 * 获取顶部导航 CMS
 */
function getTopLink() {
    var topLinks = []
    var data = [{
        contentType: '1', // 1是Banner、2是新闻、3是视频
        projectCode: '100025', // 项目编码
        resCode: 'pos00028' // 顶部外链
    }]
    $.ajax({
        type: 'post',
        url: 'https://proxy.jdl.cn/cms/queryContentListWithPage',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        cache: false,
        headers: {
            'LOP-DN': 'jdwl.com', // 使用创建的域名，否则调用不通过
            'ClientInfo': JSON.stringify({
                'appName': 'c2c', // 此处本人使用的是创建的分组名
                'client': 'm' // 客户端类型：如：apple（苹果手机），android（安卓手机），m(m页)等
            }),
            'AppParams': JSON.stringify({
                'appid': '158', // 无线登录appid
                'ticket_type': 'pc' // app(只使用app的登录态),m(只使用m的登录态),pc(只使用pc的登录态),wq(只使用wq的登录态),mix(混用方式，按app/m/pc/wq的顺序，若前者为空，则依次验证下一种登录态)
            })
        },
        success: function success(res) {
           res = JSON.parse(res)
           if (res.code !== 1) return

            if (res.data && res.data.itemList && res.data.itemList.length) {
                topLinks = res.data.itemList.map(function(item) {
                    return {
                        name: item.contentTitle,
                        link: item.link,
                        clstag: item.contentAbstract
                    }
                })
            }
            checklogin(topLinks)
        },
        error: function error(error) {
            checklogin(topLinks)
        }
    })
}

/**
 * 验证是否登录，header中显示已登录还是请登录
 */

function checklogin(topLinks) {
    $.ajax({
        type: "get",
        url: (window.env === 'dev' ? 'http' : 'https') + "://passport.jdl.cn/loginservice.aspx?method=Login",
        dataType: "jsonp",
        success: function success(data) {
            if (data.Identity.IsAuthenticated != null && data.Identity.IsAuthenticated == true) {
                var unick = data.Identity.Unick;
                $('.wrap .left').html(topLinkView(topLinks))
                $('.wrap .right').html(userLinkView(unick))
            } else {
                $('.wrap .left').html(topLinkView(topLinks))
                $('.wrap .right').html(userLinkView())
            }
        },
        error: function error(data) {
            unick = "";
            $('.wrap .left').html(topLinkView(topLinks))
            $('.wrap .right').html(userLinkView())
        }
    });
}
function goOrer() {
    location.href = "/route/orderList.do?isCnet=1";
}

function checkloginBnet() {
    $.ajax({
        type: "get",
        url: (window.env === 'dev' ? 'http' : 'https') + "://passport.jdl.cn/loginservice.aspx?method=Login",
        dataType: "jsonp",
        success: function success(data) {
            if (data.Identity.IsAuthenticated != null && data.Identity.IsAuthenticated == true) {
                var unick = data.Identity.Unick;
                localStorage.setItem("bnetLogin", "true");
            } else {
                localStorage.setItem("bnetLogin", "false");
            }
        },
        error: function error(data) {
            localStorage.setItem("bnetLogin", "false");
        }
    });
}

/**
 * 退出登录的方法，需要清理掉jdwl.com域，也需要清理jd.com域。
 */
function logout() {
    $.getJSON("//sso." + domain + "/exit?callback=?", function (data) {
        $.getJSON("//sso.jd.com/exit?callback=?", function (data) {
            // location.href = "//" + domain;
            location.href = '//' + window.location.hostname
        });
    });
}

/**
 * 查询订单逻辑
 */
function checkWayBillOrder() {

    var waybillText = jQuery.trim($("#waybillArea").val());

    var regTrue = /^[0-9A-Za-z]{10,20}$/;
    var regString = /^[A-Za-z]{10,20}$/;
    //1、非空校验
    if (waybillText.length == 0 || waybillText == "最多输入20个单号，以 , 或者 ; 号隔开") {
        // alert("对不起，您还未输入运单号！");
        $("#waybillArea").focus();
        return false;
    }

    //2、转换中文分号和逗号至英文逗号
    waybillText = waybillText.replaceAll("\"", '').replaceAll("'", ''),
        waybillText = waybillText.replaceAll(";", ",").replaceAll("，", ",").replaceAll("；", ",").replaceAll(' ', ',').replaceAll('、',',');
    //处理最后一个符号
    var lastv = waybillText.charAt(waybillText.length - 1);
    if(lastv == ','){
        waybillText = waybillText.substr(0, waybillText.length - 1);
    }

    if (waybillText.indexOf(",") > -1) {
        //判断运单是否符合规则
        var waybillCodes = waybillText.split(",");
        //校验运单是否输入超过20个
        if (waybillCodes.length > 20) {
            alert("对不起，您输入超过20个运单号");
            $("#waybillArea").focus();
            return false;
        }

        //校验每个订单的长度
        for (var i = 0; i < waybillCodes.length; i++) {
            var waybillCode = waybillCodes[i];
            // if (waybillCode.length > 20) {
            //     alert("对不起，您输入运单号太长!");
            //     return false;
            // }
            if(!regTrue.test(waybillCode)){
                alert("请输入正确的运单号");
                $("#waybillArea").focus();
                return false;
            }
            if(regString.test(waybillCode) && regTrue.test(waybillCode)){
                alert("请输入正确的运单号");
                $("#waybillArea").focus();
                return false;
            }
        }
    } else {

        if(!regTrue.test(waybillText)){
            alert("请输入正确的运单号");
            $("#waybillArea").focus();
            return false;
        }
        if(regString.test(waybillText) && regTrue.test(waybillText)){
            alert("请输入正确的运单号");
            $("#waybillArea").focus();
            return false;
        }
    }

    $("#waybillAreaon").val(waybillText);

    //3、校验是否登录
    /*if (unick == undefined || unick == null || unick == '') {
     if(confirm("请登录京东账户后再进行查询，谢谢！")){
     return location.href = loginUrl;
     }else{
     return false;
     }
     }*/
    //校验通过，执行查询请求
    $("#waybillForm").submit();
}

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};

function onlickHref(page, url) {

    if ($("#pageForm").attr("action") != null && $("#pageForm").attr("action") != "") {
        //针对表单提交的特殊处理
        var htmls = $("#pageForm").html();
        htmls += "<input type='hidden' name='page' value='" + page + "'>";
        $("#pageForm").html(htmls);
        $("#pageForm").submit();
    } else {
        window.location.href = url.replace("id.html", page + ".html");
    }
}

function queryMacr(url, page) {
    if ($("#pageForm").attr("action") != null && $("#pageForm").attr("action") != "") {
        //针对表单提交的特殊处理
        var htmls = $("#pageForm").html();
        htmls += "<input type='hidden' name='page' value='" + page + "'>";
        $("#pageForm").html(htmls);
        $("#pageForm").submit();
    } else {
        var page = page + ".html";
        window.location.href = url.replace("id.html", page);
    }
}
// 跳转到时效查询页面
function returnQueryAgingPage() {
    $("#returnQueryAgingPage").submit();
}

// 查询时效
function newQueryAging() {
    var start = $("#city-picker3").val();
    var end = $("#city-picker4").val();
    var agingWeight = $("#aging-weight").val();
    var datetimepicker = $("#datetimepicker").val();
    var regular = /^\+?[1-9][0-9]*$/;
    if (start == null || start == "") {
        alert("寄件地不能为空");
        return;
    }
    if (end == null || end == "") {
        alert("目的地不能为空");
        return;
    }
    if (agingWeight == null || agingWeight == "" || agingWeight == 0) {
        alert("重量不能为空和0");
        return;
    }
    if (!regular.test(agingWeight)) {
        alert("重量只能输入非0开头的正整数");
        return;
    }
    if (datetimepicker == "" || datetimepicker.length == 0) {
        alert("请选择寄件时间");
        return;
    }
    var dateAndTimeArr = datetimepicker.split(" "),
        dateArr = dateAndTimeArr[0].split('/'),
        timeArr = dateAndTimeArr[1].split(':');
    var date = new Date();
    date.setFullYear(dateArr[0]), date.setMonth(dateArr[1] - 1), date.setDate(dateArr[2]), date.setHours(timeArr[0]), date.setMinutes(timeArr[1]);
    var startArray = start.split("/");
    var endArray = end.split("/");
    var startProvince, startCity, startCounty, startTown;
    var endProvince, endCity, endCounty, endTown;
    if (startArray.length != 3 || endArray.length != 3) {
        alert("寄件地和目的地必须输入到三级地址");
        return;
    }
    if (startArray.length == 3) {
        startProvince = parseInt(startArray[0]);
        startCity = parseInt(startArray[1]);
        startCounty = parseInt(startArray[2]);
    }
    if (endArray.length == 3) {
        endProvince = parseInt(endArray[0]);
        endCity = parseInt(endArray[1]);
        endCounty = parseInt(endArray[2]);
    }
    $("body").mLoading('show');
    var data = {
        cityAgingExt: JSON.stringify({ startProvinceId: startProvince, startCityId: startCity, startCountryId: startCounty, endProvinceId: endProvince,
            endCityId: endCity, endCountryId: endCounty, dateTime: date.getTime() }),
        freightsRequest: JSON.stringify({ sendProvinceId: startProvince, sendCityId: startCity, sendCountyId: startCounty, receiveProvinceId: endProvince,
            receiveCityId: endCity, receiveCountyId: endCounty, weight: agingWeight })
    };
    $.ajax({
        type: "post",
        url: "/aging/newQueryAging",
        data: data,
        success: function success(data) {
            if (data.length) {
                $("body").mLoading('hide');
                var agingResult = $("#aging-result");
                agingResult.css("display", "table");
                agingResult.empty();
                if (data.length == 0) {
                    $("#no-aging-message").css("display", "block");
                    return;
                } else {
                    $("#no-aging-message").css("display", "none");
                }
                var agingResult = $("#aging-result");
                agingResult.empty();
                var agingTr = "<thead><tr>" + "<th>产品类型</th>" + "<th>重量(KG)</th>" + "<th>预计到达时效</th>" + "<th>价格(元)</th>" + "</tr></thead>" + "<tbody>";

                for (var o in data) {
                    agingTr = agingTr + "<tr>" + "<td>" + data[o].productName + "</td>" + "<td>" + data[o].weight + "</td>" + "<td>" + data[o].deliveryDate + "</td>" + "<td>" + data[o].freight + "</td>" + "</tr>";
                }
                agingTr = agingTr + "</tbody>";
                agingResult.append(agingTr);
            } else {
                $("#aging-result").css("display", "none");
                $("#no-aging-message").css("display", "block");
                return;
            }
        },
        error: function error(errres) {}
    });
}
//function queryAging() {
//
//    var start = $("#city-picker3").val();
//    var end = $("#city-picker4").val();
//    var agingWeight = $("#aging-weight").val();
//    var datetimepicker = $("#datetimepicker").val();
//    var regular = /^\+?[1-9][0-9]*$/;
//    if (start == null || start == "") {
//        alert("寄件地不能为空");
//        return;
//    }
//    if (end == null || end == "") {
//        alert("目的地不能为空");
//        return;
//    }
//    if (agingWeight == null || agingWeight == "" || agingWeight == 0) {
//        alert("重量不能为空和0");
//        return;
//    }
//    if (!regular.test(agingWeight)) {
//        alert("重量只能输入非0开头的正整数");
//        return;
//    }
//    if (datetimepicker == "" || datetimepicker.length == 0) {
//        alert("请选择寄件时间");
//        return;
//    }
//    var startArray = start.split("/");
//    var endArray = end.split("/");
//    var startProvince, startCity, startCounty, startTown;
//    var endProvince, endCity, endCounty, endTown;
//    if (startArray.length != 3 || endArray.length != 3) {
//        alert("寄件地和目的地必须输入到三级地址");
//        return;
//    }
//    if (startArray.length == 3) {
//        startProvince = startArray[0];
//        startCity = startArray[1];
//        startCounty = startArray[2];
//    }
//    if (endArray.length == 3) {
//        endProvince = endArray[0];
//        endCity = endArray[1];
//        endCounty = endArray[2];
//    }
//    $("body").mLoading('show');
//    $.ajax({
//        type: "post",
//        url: "/aging/query-aging",
//        data: {
//            startProvince: startProvince,
//            startCity: startCity,
//            startCounty: startCounty,
//            endProvince: endProvince,
//            endCity: endCity,
//            endCounty: endCounty,
//            weight: agingWeight,
//            shipmentTime: datetimepicker
//        },
//        async: true,
//        success: function success(data) {
//            $("body").mLoading('hide');
//            var agingResult = $("#aging-result");
//            agingResult.empty();
//            if (data.length == 0) {
//                $("#no-aging-message").css("display", "block");
//                return;
//            } else {
//                $("#no-aging-message").css("display", "none");
//            }
//            var agingResult = $("#aging-result");
//            agingResult.empty();
//            var agingTr = "<thead><tr>" + "<th>产品类型</th>" + "<th>重量(KG)</th>" + "<th>预计到达时效</th>" + "<th>价格(元)</th>" + "</tr></thead>" + "<tbody>";
//
//            for (var o in data) {
//                agingTr = agingTr + "<tr>" + "<td>" + data[o].productType + "</td>" + "<td>" + data[o].weight + "</td>" + "<td>" + data[o].deliveredDate + "</td>" + "<td>" + data[o].freight + "</td>" + "</tr>";
//            }
//            agingTr = agingTr + "</tbody>";
//            agingResult.append(agingTr);
//        },
//        error: function error(data) {
//            $(".form").mLoading('hide');
//        }
//    });
//}
var requestParam = {
    deliveryId: '',
    telephone: '',
    source: '1',
    verificationCode: ''
};
var start = 60;
var interval = null;
localStorage.setItem("timeCur", start);
function signImgQry(deliveryId) {
    var startTime = localStorage.getItem("timeCur") || start;
    startTime = parseInt(startTime);
    if (startTime == 0) {
        startTime = 60;
    }
    if (startTime !== 60) {
        $('#timeText').text(startTime);
        $('#verifyGet').css('display', 'none');
        $('#secShow').css('display', '');
        computedSec();
    } else {
        localStorage.setItem("timeCur", start);
    }
    requestParam.deliveryId = deliveryId;
    $('.elec-mask').css('display', '');
    $('#signInput').css('display', '');
}
$(function () {
    var main_level = sessionStorage.getItem('main-level');
    if (main_level) {
        $('#' + main_level).addClass('cur');
    }
    $('.main-level').bind('click', function () {
        var id = $(this).attr('id');
        sessionStorage.setItem('main-level', id);
        $(this).addClass('cur');
    });
    $('.main-level').hover(function () {
        $(this).siblings().removeClass('cur');
    });

    //签名查询-弹层
    $('.btn-sign').on('click', function () {
        var deliveryId = $(this).attr('id');
        $('.maskLayout').fadeIn();
        $('#modal-verify').fadeIn();
        var startTime = localStorage.getItem("timeCur") || start;
        startTime = parseInt(startTime);
        if (startTime == 0) {
            startTime = 60;
        }
        if (startTime !== 60) {
            $('#timeText').text(startTime);
            computedSec();
        } else {
            localStorage.setItem("timeCur", start);
        }
        requestParam.deliveryId = deliveryId;
    });
    $('#timeText').off('click').on('click',function(){
        getPhoneVerifyCode();
    });
    $('.m-modal .close').on('click', function () {
        $(this).closest('.m-modal').fadeOut();
        $('.maskLayout').fadeOut();
    });
    $('.m-submit .cancel').on('click', function () {
        $(this).closest('.m-modal').fadeOut();
        $('.maskLayout').fadeOut();
    });
    $('.m-submit .confim').on('click', function () {
        var phoneNum = $('#phoneNum').val();
        if (phoneNum.length == 0) {
            alert('请输入手机号！');
            return;
        }
        if (!verifyPhone(phoneNum)) {
            alert('手机号格式不对，请检查');
            return;
        }
        requestParam.telephone = phoneNum;
        var verifyCode = $('#verifyIn').val();
        if (verifyCode.length == 0) {
            alert('请输入验证码！');
            return;
        }
        requestParam.verificationCode = verifyCode;
        $.ajax({
            url: '/order/getSignImg',
            data: { deliveryId: requestParam.deliveryId, telephone: requestParam.telephone, verificationCode: requestParam.verificationCode },
            method: 'post',
            success: function success(res) {
                try {
                    clearInterval(interval);
                    localStorage.setItem("timeCur", start);
                    $('#verifyIn').val('');
                    var result = JSON.parse(res);
                    if (result.statusCode == 0 && result.data) {
                        var imgData = result.data;
                        $('#elec_logisNumber').text(imgData.deliveryId);
                        $('#elec_time').text(formatTime(new Date(imgData.operateTime)));
                        $('#elec_img').attr('src', 'data:image/png;base64, ' + imgData.signatureImage);
                        $('#signImg').css('display', '');
                        $('#timeText').text('获取验证码');

                        $('#modal-verify').fadeOut();
                        $('#modal-signature').fadeIn();
                    } else {
                        $('#modal-verify,.maskLayout').fadeOut();
                        alert(result.statusMessage);
                        return;
                    }
                } catch (ex) {
                    $('#modal-verify,.maskLayout').fadeOut();
                    alert('未查询到此运单的电子签名，请确认');
                    return;
                }
            },
            error: function error(err) {}
        });
    });
});
function getPhoneVerifyCode() {
    var that = this;
    var phoneNum = $('#phoneNum').val();
    if (phoneNum.length == 0) {
        alert('请输入手机号！');
        return;
    }
    if (!verifyPhone(phoneNum)) {
        alert('手机号格式不对，请检查');
        return;
    }
    requestParam.telephone = phoneNum;
    $.ajax({
        url: '/order/getPhoneVerify',
        data: { deliveryId: requestParam.deliveryId, telephone: requestParam.telephone },
        method: 'post',
        success: function success(res) {
            var result = JSON.parse(res);
            console.log(result instanceof Object);
            console.log(result.status);
            if (result.statusCode == 0) {
                $('#verifyGet').css('display', 'none');
                $('#secShow').css('display', '');
                var timeBegin = localStorage.getItem("timeCur");
                timeBegin == 0 ? start : timeBegin;
                $('#timeText').text(timeBegin);
                computedSec();
            } else {
                alert(result.statusMessage);
            }
        },
        error: function error(err) {}
    });
}
function submitElecSignInput(deliveryId, telephone) {
    var phoneNum = $('#phoneNum').val();
    if (phoneNum.length == 0) {
        alert('请输入手机号！');
        return;
    }
    if (!verifyPhone(phoneNum)) {
        alert('手机号格式不对，请检查');
        return;
    }
    requestParam.telephone = phoneNum;
    var verifyCode = $('#verifyIn').val();
    if (verifyCode.length == 0) {
        alert('请输入验证码！');
        return;
    }
    requestParam.verificationCode = verifyCode;
    $.ajax({
        url: '/order/getSignImg',
        data: { deliveryId: requestParam.deliveryId, telephone: requestParam.telephone, verificationCode: requestParam.verificationCode },
        method: 'post',
        success: function success(res) {
            try {
                $('#verifyGet').css('display', '');
                $('#secShow').css('display', 'none');
                clearInterval(interval);
                localStorage.setItem("timeCur", start);
                $('#verifyIn').val('');
                var result = JSON.parse(res);
                if (result.statusCode == 0 && result.data) {
                    var imgData = result.data;
                    $('#signInput').css('display', 'none');
                    $('#elec_logisNumber').text(imgData.deliveryId);
                    $('#elec_time').text(formatTime(new Date(imgData.operateTime)));
                    $('#elec_img').attr('src', 'data:image/png;base64, ' + imgData.signatureImage);
                    $('#signImg').css('display', '');

                    $('#modal-verify').fadeOut();
                    $('#modal-signature').fadeIn();
                } else {
                    $('#modal-verify,.maskLayout').fadeOut();
                    alert(result.statusMessage);
                    return;
                    //cancel();
                }
            } catch (ex) {
                $('#modal-verify,.maskLayout').fadeOut();
                alert('未查询到此运单的电子签名，请确认');
                return;
            }
        },
        error: function error(err) {}
    });
}

function cancel() {
    $('.elec-dialog').css('display', 'none');
    $('.elec-mask').css('display', 'none');
}

function computedSec() {
    clearInterval(interval);
    interval = setInterval(function () {
        var timeBegin = localStorage.getItem("timeCur");
        console.log(timeBegin);
        if (parseInt(timeBegin) > 0) {
            timeBegin = parseInt(timeBegin) - 1;
            $('#timeText').text(timeBegin);
            localStorage.setItem("timeCur", timeBegin);
        } else {
            localStorage.setItem("timeCur", timeBegin);
            clearInterval(interval);
            $('#secShow').css('display', 'none');
            $('#verifyGet').css('display', '');
        }
    }, 1000);
}
function submitElecSignInput() {}

function formatTime(source) {
    var src = source || new Date();
    var year = src.getFullYear();
    var mon = src.getMonth() + 1;
    mon = mon < 10 ? "0" + mon : mon;
    var day = src.getDate();
    day = day < 10 ? "0" + day : day;
    var hh = src.getHours();
    hh = hh < 10 ? "0" + hh : hh;
    var mm = src.getMinutes();
    mm = mm < 10 ? "0" + mm : mm;
    var sec = src.getSeconds();
    sec = sec < 10 ? "0" + sec : sec;
    return year + '-' + mon + '-' + day + ' ' + hh + ':' + mm + ':' + sec;
}
function verifyPhone(phone) {
    var reg = /^(((13[0-9]{1})|(14[579]{1})|(15[0-3,5-9]{1})|(16[6]{1})|(17[0135678]{1})|(18[0-9]{1})|(19[89]{1}))+\d{8})$/;
    return reg.test(phone);
}
function computedSec() {
    clearInterval(interval);
    interval = setInterval(function () {
        var timeBegin = localStorage.getItem("timeCur");
        console.log(timeBegin);
        if (parseInt(timeBegin) > 0) {
            timeBegin = parseInt(timeBegin) - 1;
            $('#timeText').text(timeBegin);
            localStorage.setItem("timeCur", timeBegin);
        } else {
            localStorage.setItem("timeCur", timeBegin);
            clearInterval(interval);
            $('#timeText').text('获取验证码');
        }
    }, 1000);
}
var distance,
    spherical = qq.maps.geometry.spherical;
function productMap(id) {
    var finshMarkerPoints = [],
        firstLoadMap = true,
        toPoint,
        nextFinshMarkers = [],
        tempOverPoint,
        gpsTime;
    var mapContaint = document.getElementById("locus-cont_" + id);
    //let tmpId=$('#waybillArea').val();
    $.ajax({
        url: '/order/getWaybillNodeTrack',
        data: { waybillCode: id },
        method: 'post',
        success: function success(json) {
            console.log(json);
            if (json == "") {
                $("#box_" + id).hide();
                return;
            }
            var res = JSON.parse(json) || {};
            if (res.showMapFlag) {
                finshMarkerPoints = [];
                nextFinshMarkers = [];
                var firstUnfinshPoint = null;
                var tmap = new qq.maps.Map(mapContaint, {
                    center: new qq.maps.LatLng(39.914850, 116.403765),
                    zoom: 13,
                    draggable: true,
                    scrollwheel: true,
                    disableDoubleClickZoom: false
                });
                var info = new qq.maps.Label({
                    map: tmap,
                    style: { color: '#fff', fontSize: '14px', backgroundColor: '#000', opacity: '0.65', borderRadius: '4px' }
                });
                var markerList = [];
                var waybillNodeDtoList = res.waybillNodeDtoList || [];
                if (waybillNodeDtoList.length) {
                    toPoint = waybillNodeDtoList[waybillNodeDtoList.length - 1].lat + "," + waybillNodeDtoList[waybillNodeDtoList.length - 1].lng;
                }
                //if(waybillNodeDtoList[waybillNodeDtoList.length-1].nodeMapType==8){
                var recImg = getImgIcon(waybillNodeDtoList[waybillNodeDtoList.length - 1].nodeMapType),
                    recIcon = new qq.maps.MarkerImage(recImg),
                    recPosition = new qq.maps.LatLng(waybillNodeDtoList[waybillNodeDtoList.length - 1].lat, waybillNodeDtoList[waybillNodeDtoList.length - 1].lng),
                    recMarker = new qq.maps.Marker({
                        position: recPosition,
                        map: tmap,
                        icon: recIcon
                    });
                var addressname = '';
                if (waybillNodeDtoList[waybillNodeDtoList.length - 1].nodeMapType == 8) {
                    addressname = '收货地址';
                } else if (waybillNodeDtoList[waybillNodeDtoList.length - 1].nodeMapType == 7) {
                    addressname = '便民点';
                } else if (waybillNodeDtoList[waybillNodeDtoList.length - 1].nodeMapType == 6) {
                    addressname = '自提柜';
                } else if (waybillNodeDtoList[waybillNodeDtoList.length - 1].nodeMapType == 5) {
                    addressname = '自提点';
                }
                addEventForMarker(recMarker, info, addressname, recPosition);
                //}
                for (var i = 0; i < waybillNodeDtoList.length - 1; i++) {
                    if (!waybillNodeDtoList[i].lat || !waybillNodeDtoList[i].lng) {
                        continue;
                    }
                    var imgUrl = getImgIcon(waybillNodeDtoList[i].nodeMapType);
                    var icon = new qq.maps.MarkerImage(imgUrl);
                    var position = new qq.maps.LatLng(waybillNodeDtoList[i].lat, waybillNodeDtoList[i].lng);
                    var marker = new qq.maps.Marker({
                        position: position,
                        map: tmap
                    });
                    marker.setIcon(icon);
                    var nodeName = waybillNodeDtoList[i].nodeMapType == 8 ? '收货地址' : waybillNodeDtoList[i].nodeName;
                    addEventForMarker(marker, info, nodeName, position);
                    if (!res.waybillFinishFlag) {
                        if (firstLoadMap) {
                            if (waybillNodeDtoList[i].nodeFinishFlag) {
                                finshMarkerPoints.push(position);
                            }
                        } else {
                            if (waybillNodeDtoList[i].nodeFinishFlag) {
                                nextFinshMarkers.push(position);
                            }
                        }
                    } else {
                        finshMarkerPoints.push(position);
                    }
                    if (!waybillNodeDtoList[i].nodeFinishFlag && !res.waybillFinishFlag) {
                        tempOverPoint = position;
                        break;
                    }
                }
                if (res.waybillFinishFlag || waybillNodeDtoList[waybillNodeDtoList.length - 1].nodeFinishFlag) {
                    finshMarkerPoints.push(recPosition);
                }
                //pixelEnd=new qq.maps.LatLng(waybillNodeDtoList[finshMarkerPoints.length-1].lat, waybillNodeDtoList[finshMarkerPoints.length-1].lng);
                var tempPoints = [];
                if (firstLoadMap) {
                    getRouteLines(finshMarkerPoints, firstLoadMap, tmap);
                    if (!res.waybillFinishFlag) {
                        if (!tempOverPoint) {
                            tempOverPoint = new qq.maps.LatLng(waybillNodeDtoList[waybillNodeDtoList.length - 1].lat, waybillNodeDtoList[waybillNodeDtoList.length - 1].lng);
                        }
                        tempPoints.push(finshMarkerPoints[finshMarkerPoints.length - 1]);
                        tempPoints.push(tempOverPoint);
                    } else {
                        fitAllPoints(finshMarkerPoints, tmap, id);
                    }
                } else {
                    if (nextFinshMarkers.length > 0 && nextFinshMarkers.length != finshMarkerPoints.length) {
                        var _tmpArr = nextFinshMarkers.splice(0, finshMarkerPoints.length);
                        _tmpArr.unshift(finshMarkerPoints[finshMarkerPoints.length - 1]);
                    }
                    for (var _i = 0; _i < tmpArr.length - 1; _i++) {
                        tempPoints.push(tmpArr[_i]);
                        tempPoints.push(tmpArr[_i + 1]);
                        if (_i == 0) {
                            getRoutePoyLine(tmap, tempPoints, firstLoadMap);
                        } else {
                            getRoutePoyLine(tmap, tempPoints, firstLoadMap);
                        }
                    }
                }
                if (!res.waybillFinishFlag) {
                    firstUnfinshPoint = res.waybillNodeDtoList[finshMarkerPoints.length];
                    var centerMarker = new qq.maps.Marker({
                        map: tmap
                    });
                    getGisInfo(id, tempPoints, info, tmap, firstUnfinshPoint, gpsTime, finshMarkerPoints, firstLoadMap, tempOverPoint, toPoint, centerMarker);
                }
            }
        },
        error: function error(json) {}
    });
}
function getGisInfo(id, tmpLinePoints, info, tmap, firstUnfinshPoint, gpsTime, finshMarkerPoints, firstLoadMap, tempOverPoint, toPoint, centerMarker, lastP) {
    var dataParam = { waybillCode: id },
        lineMarkerPoints = [],
        lastMarkerPoint = void 0,
        lastPoint = lastP,
        gpsFrequency = 120,
        speed = new Number(75),
        timerInterval = void 0,
        fromPoint = void 0,
        pixelEnd = void 0,
        movingstart = void 0,
        pathArr = [];
    if (gpsTime && !firstLoadMap) {
        dataParam.gpsTime = gpsTime;
    }
    $.ajax({
        url: '/order/getWaybillGisTrack',
        data: dataParam,
        method: 'post',
        success: function success(json) {
            console.log(json);
            if (json != '') {
                var res = JSON.parse(json);
                var waybillNodeDtoList = [],
                    list = res.waybillGisDtoList;
                if (list && parseInt(res.gpsSource) < 3) {
                    if (!res.waybillFinishFlag) {
                        if (!list) {
                            fitAllPoints(tmpLinePoints, tmap, id);
                            return;
                        }
                        for (var i = 0; i < list.length; i++) {
                            if (i == 0) {
                                waybillNodeDtoList.push(list[i]);
                            } else {
                                if (list[i - 1].lat != list[i].lat || list[i - 1].lng != list[i].lng) {
                                    waybillNodeDtoList.push(list[i]);
                                }
                            }
                        }
                        var lastLen = waybillNodeDtoList.length;
                        if (waybillNodeDtoList[lastLen - 1].gpsTime) {
                            gpsTime = waybillNodeDtoList[lastLen - 1].gpsTime;
                            sessionStorage.setItem(id + "_gpsTime", gpsTime);
                        }
                        var pixelStart = new qq.maps.LatLng(waybillNodeDtoList[lastLen - 1].lat, waybillNodeDtoList[lastLen - 1].lng);
                        movingstart = new qq.maps.LatLng(waybillNodeDtoList[0].lat, waybillNodeDtoList[0].lng);
                        if (lastLen > 1) {
                            pixelStart = new qq.maps.LatLng(waybillNodeDtoList[0].lat, waybillNodeDtoList[0].lng);
                            pixelEnd = new qq.maps.LatLng(waybillNodeDtoList[lastLen - 1].lat, waybillNodeDtoList[lastLen - 1].lng);
                        } else {
                            if (firstLoadMap) {
                                pixelEnd = new qq.maps.LatLng(tempOverPoint.lat, tempOverPoint.lng);
                            } else {
                                pixelStart = lastPoint;
                                pixelEnd = new qq.maps.LatLng(waybillNodeDtoList[lastLen - 1].lat, waybillNodeDtoList[lastLen - 1].lng);
                            }
                        }
                        fromPoint = waybillNodeDtoList[lastLen - 1].lat + "," + res.waybillGisDtoList[lastLen - 1].lng;
                        pathArr = [];
                        if (lastLen) {
                            if (lastPoint) {
                                pathArr.push(lastPoint);
                            }
                            if (lastLen > 1) {
                                for (var _i2 = 0; _i2 < lastLen; _i2++) {
                                    pathArr.push(new qq.maps.LatLng(waybillNodeDtoList[_i2].lat, waybillNodeDtoList[_i2].lng));
                                }
                            } else if (pathArr.length) {
                                if (waybillNodeDtoList[0].lat != lastPoint.lat || waybillNodeDtoList[0].lng != lastPoint.lng) {
                                    pathArr.push(new qq.maps.LatLng(waybillNodeDtoList[0].lat, waybillNodeDtoList[0].lng));
                                }
                            }
                        }
                        var distanceM = spherical.computeDistanceBetween(pixelStart, pixelEnd); //计算两经纬度坐标件的距离
                        console.log('distanceM::' + distanceM);
                        console.log(speed);
                        if (distanceM) {
                            speed = parseInt(distanceM / gpsFrequency * 3.6);
                            speed = speed > 80 ? 80 : speed;
                            speed = speed < 60 ? 60 : speed;
                        }
                        console.log(speed);
                        if (firstLoadMap) {
                            lastPoint = new qq.maps.LatLng(waybillNodeDtoList[lastLen - 1].lat, waybillNodeDtoList[lastLen - 1].lng);
                            tmpLinePoints.push(lastPoint);
                            var centerPoint = new qq.maps.LatLng(waybillNodeDtoList[0].lat, waybillNodeDtoList[0].lng);
                            tmap.setCenter(centerPoint);
                            var imgUrl = '',
                                icon = void 0;
                            if (res.gpsSource == 1) {
                                var anchor = new qq.maps.Point(25, 25),
                                    size = new qq.maps.Size(60, 110),
                                    origin = new qq.maps.Point(0, 0),
                                    scaleSize = new qq.maps.Size(30, 55),
                                    _imgUrl = '/resource/css/img/locus/transfercar.png';
                                icon = new qq.maps.MarkerImage(_imgUrl, size, origin, anchor, scaleSize);
                            } else if (res.gpsSource == 2) {
                                speed = new Number(20);
                                imgUrl = '/resource/css/img/locus/psy.png';
                                icon = new qq.maps.MarkerImage(imgUrl);
                            }
                            centerMarker.setIcon(icon);
                            centerMarker.setPosition(centerPoint);
                            addEventForMarker(centerMarker, info, "\u5F53\u524D\u4F4D\u7F6E\u8DDD\u79BB\u7EC8\u70B9 " + distance + " Km", centerPoint, tmap, id, firstUnfinshPoint, waybillNodeDtoList[lastLen - 1].gpsTime, finshMarkerPoints, tempOverPoint, toPoint, movingstart);
                            getRouteLines(finshMarkerPoints, firstLoadMap, tmap);
                            fitAllPoints(tmpLinePoints, tmap, id);
                        } else {
                            lastPoint = new qq.maps.LatLng(waybillNodeDtoList[lastLen - 1].lat, waybillNodeDtoList[lastLen - 1].lng);
                            if (lastMarkerPoint && (lastMarkerPoint.lat != finshMarkerPoints[finshMarkerPoints.length - 1].lat || lastMarkerPoint.lng != finshMarkerPoints[finshMarkerPoints.length - 1].lng)) {
                                lineMarkerPoints = [];
                                lineMarkerPoints.push(lastMarkerPoint);
                                lineMarkerPoints.push(finshMarkerPoints[finshMarkerPoints.length - 1]);
                                getRoutePoyLine(tmap, lineMarkerPoints, firstLoadMap);
                            }
                        }
                        if (pathArr.length > 1) {
                            clearInterval(timerInterval);
                            centerMarker.moveAlong(pathArr, speed);
                        } else {
                            var _pixelStart = new qq.maps.LatLng(waybillNodeDtoList[0].lat, waybillNodeDtoList[0].lng),
                                _pixelEnd = new qq.maps.LatLng(firstUnfinshPoint.lat, firstUnfinshPoint.lng);
                            var _distance = spherical.computeDistanceBetween(_pixelStart, _pixelEnd); //计算两经纬度坐标件的距离
                            var heading = spherical.computeHeading(_pixelStart, _pixelEnd); //两经纬度坐标点之间的航向
                            var rotation = computeRotaion(heading); //由两坐标点之间的航向计算marker要旋转的角度
                            if (rotation) {
                                centerMarker.setRotation(rotation);
                            }
                            timerInterval = setInterval(function () {
                                getGisInfo(id, null, info, tmap, firstUnfinshPoint, waybillNodeDtoList[lastLen - 1].gpsTime, finshMarkerPoints, false, tempOverPoint, toPoint, centerMarker, lastPoint);
                                clearInterval(timerInterval);
                            }, 10 * 1000);
                            $("#locus-cont_c_" + id).find('.close').attr('id', timerInterval);
                        }
                        ;
                        computeDistance(fromPoint, toPoint, 'getdistance');
                    } else {
                        productMap(id);
                    }
                } else {
                    tmap.setCenter(new qq.maps.LatLng(finshMarkerPoints[finshMarkerPoints.length - 1].lat, finshMarkerPoints[finshMarkerPoints.length - 1].lng));
                    if (firstUnfinshPoint) {
                        var path = [new qq.maps.LatLng(finshMarkerPoints[finshMarkerPoints.length - 1].lat, finshMarkerPoints[finshMarkerPoints.length - 1].lng), new qq.maps.LatLng(firstUnfinshPoint.lat, firstUnfinshPoint.lng)];
                        var polygon = new qq.maps.Polyline({
                            map: tmap,
                            path: path,
                            strokeColor: '#f88566',
                            strokeWeight: 6,
                            strokeDashStyle: 'dash'
                        });
                    }
                    fitAllPoints(tmpLinePoints, tmap, id);
                }
            } else {
                tmap.setCenter(new qq.maps.LatLng(finshMarkerPoints[finshMarkerPoints.length - 1].lat, finshMarkerPoints[finshMarkerPoints.length - 1].lng));
                if (firstUnfinshPoint) {
                    var path = [new qq.maps.LatLng(finshMarkerPoints[finshMarkerPoints.length - 1].lat, finshMarkerPoints[finshMarkerPoints.length - 1].lng), new qq.maps.LatLng(firstUnfinshPoint.lat, firstUnfinshPoint.lng)];
                    var polygon = new qq.maps.Polyline({
                        map: tmap,
                        path: path,
                        strokeColor: '#f88566',
                        strokeWeight: 6,
                        strokeDashStyle: 'dash'
                    });
                }
                fitAllPoints(tmpLinePoints, tmap, id);
            }
        },
        error: function error() {}
    });
}

function getImgIcon(nodeMapType) {
    var imgUrl = '';
    if (nodeMapType == 1) {
        imgUrl = "/resource/css/img/locus/pickcenter.png";
    } else if (nodeMapType == 2) {
        imgUrl = "/resource/css/img/locus/pickcenter.png";
    } else if (nodeMapType == 3) {
        imgUrl = "/resource/css/img/locus/selfstation.png";
    } else if (nodeMapType == 4) {
        imgUrl = "/resource/css/img/locus/selfstation.png";
    } else if (nodeMapType == 5) {
        imgUrl = "/resource/css/img/locus/distribution.png";
    } else if (nodeMapType == 6) {
        imgUrl = "/resource/css/img/locus/selfcupboard.png";
    } else if (nodeMapType == 7) {
        //此处无便民点的概念
        imgUrl = "/resource/css/img/locus/handystation.png";
    } else if (nodeMapType == 8) {
        imgUrl = "/resource/css/img/locus/recaddr.png";
    } else if (nodeMapType == 9) {
        imgUrl = "/resource/css/img/locus/sender.png";
    } else {
        imgUrl = "/resource/css/img/locus/normal.png";
    }
    return imgUrl;
}
function getdistance(jsonp) {
    console.log(jsonp);
    if (jsonp.status == 0) {
        var distaceObj = jsonp.result.routes[0];
        distance = Math.ceil(distaceObj.distance / 1000);
    }
}
function computeRotaion(heading) {
    var rotation = void 0;
    if (heading < 0) {
        rotation = 360 + heading;
    } else {
        rotation = heading;
    }
    return rotation;
}
//清除地图上的marker
function clearOverlay(overlays) {
    var overlay;
    while (overlay = overlays.pop()) {
        overlay.setMap(null);
    }
}
function getRoutePoyLine(map, finshPoints, firstLoadMap) {
    if (finshPoints.length == 1) {
        return;
    }
    var directionsService = new qq.maps.DrivingService({
            complete: function complete(response) {}
        }),
        directions_routes,
        start_marker,
        end_marker,
        route_lines = [];
    directionsService.search(finshPoints[0], finshPoints[finshPoints.length - 1]);
    directionsService.setComplete(function (response) {
        var start = response.detail.start,
            end = response.detail.end;
        if (firstLoadMap) {
            clearOverlay(route_lines);
        }
        directions_routes = response.detail.routes;
        var routes_desc = [];
        //所有可选路线方案
        for (var i = 0; i < directions_routes.length; i++) {
            var route = directions_routes[i],
                legs = route;
            //调整地图窗口显示所有路线
            //所有路程信息
            var polyline = new qq.maps.Polyline({
                path: route.path,
                strokeColor: '#f88566',
                strokeWeight: 6,
                map: map
            });
            route_lines.push(polyline);
        }
    });
}
function computeDistance(from, to, callback) {
    $.ajax({
        url: "//apis.map.qq.com/ws/direction/v1/driving/?from=" + from + "&to=" + to + "&output=jsonp&callback=" + callback + "&key=37RBZ-6DN66-N2KSK-EH6MX-VAV3F-QLBYJ",
        dataType: 'jsonp',
        type: 'get',
        success: function success(jsonp) {
            console.log(jsonp);
        }
    });
}

function getRouteLines(points, firstFlag, tmap) {
    if (points.length > 2) {
        var lastMarkerPoint = points[points.length - 1];
        for (var i = 0; i < points.length - 1; i++) {
            var tmpLinePoints = [];
            tmpLinePoints.push(points[i]);
            tmpLinePoints.push(points[i + 1]);
            if (i == 0) {
                getRoutePoyLine(tmap, tmpLinePoints, true);
            } else {
                getRoutePoyLine(tmap, tmpLinePoints, false);
            }
        }
    } else if (points.length == 2) {
        getRoutePoyLine(tmap, points, firstFlag);
    }
}
function addEventForMarker(marker, info, nodeName, position, tmap, id, firstUnfinshPoint, gpsTime, finshMarkerPoints, tempOverPoint, toPoint, movingstart) {
    if (nodeName.indexOf('当前位置距离终') > -1) {
        var bounds = void 0;
        qq.maps.event.addListener(tmap, 'bounds_changed', function () {
            bounds = tmap.getBounds();
        });
        var centerMarkerInfo = new qq.maps.Label({
            map: tmap,
            style: { color: '#fff', fontSize: '14px', backgroundColor: '#000', opacity: '0.65', borderRadius: '4px' },
            offset: new qq.maps.Size(5, -50)
        });
        centerMarkerInfo.setPosition(position);
        centerMarkerInfo.setVisible(false);
        qq.maps.event.addListener(marker, 'mouseover', function () {
            if (distance) {
                centerMarkerInfo.setContent("<div style=\"text-align:center;white-space:nowrap;margin:10px;\">\u5F53\u524D\u4F4D\u7F6E\u8DDD\u79BB\u7EC8\u70B9 " + distance + " Km</div>");
                centerMarkerInfo.setVisible(true);
            }
        });
        qq.maps.event.addListener(marker, 'mouseout', function () {
            centerMarkerInfo.setPosition(marker.getPosition());
            centerMarkerInfo.setVisible(false);
        });
        qq.maps.event.addListener(marker, 'moving', function (json) {
            bounds = tmap.getBounds();
            if (!bounds.contains(json.latLng)) {
                tmap.panTo(json.latLng);
            }
            centerMarkerInfo.setPosition(json.latLng);
            var pixelStart = movingstart,
                pixelEnd = json.latLng;
            var distance = spherical.computeDistanceBetween(pixelStart, pixelEnd); //计算两经纬度坐标件的距离
            var heading = spherical.computeHeading(pixelStart, pixelEnd); //两经纬度坐标点之间的航向
            var rotation = computeRotaion(heading); //由两坐标点之间的航向计算marker要旋转的角度
            if (rotation) {
                marker.setRotation(rotation);
            }
            movingstart = pixelEnd;
        });
        qq.maps.event.addListener(marker, 'moveend', function (json) {
            var gt = sessionStorage.getItem(id + "_gpsTime");
            getGisInfo(id, null, info, tmap, firstUnfinshPoint, gt, finshMarkerPoints, false, tempOverPoint, toPoint, marker, json.latLng);
        });
    } else {
        qq.maps.event.addListener(marker, 'mouseover', function () {
            info.setContent("<div style=\"text-align:center;white-space:nowrap;margin:10px;\">" + nodeName + "</div>");
            info.setPosition(position);
            info.setVisible(true);
        });
        qq.maps.event.addListener(marker, 'mouseout', function () {
            info.setVisible(false);
        });
    }
}

function setZoom(maxPoint, minPoint, tmap, id) {
    var directionsService = new qq.maps.DrivingService({
        complete: function complete(response) {}
    });
    directionsService.search(new qq.maps.LatLng(maxPoint.lat, maxPoint.lng), new qq.maps.LatLng(minPoint.lat, minPoint.lng));
    directionsService.setComplete(function (response) {
        tmap.fitBounds(response.detail.bounds);
        $("#box_" + id).hide();
    });
    directionsService.setError(function(){
        var bounds = new qq.maps.LatLngBounds(minPoint, maxPoint);
        tmap.fitBounds(bounds);
        $("#box_" + id).hide();
    })
}
function fitAllPoints(points, tmap, id) {
    if (points.length > 0) {
        var maxLng = points[0].lng;
        var minLng = points[0].lng;
        var maxLat = points[0].lat;
        var minLat = points[0].lat;
        var res;
        for (var i = points.length - 1; i >= 0; i--) {
            res = points[i];
            if (res.lng > maxLng) maxLng = res.lng;
            if (res.lng < minLng) minLng = res.lng;
            if (res.lat > maxLat) maxLat = res.lat;
            if (res.lat < minLat) minLat = res.lat;
        };
        var maxPoint = new qq.maps.LatLng(maxLat, maxLng); // 创建点坐标A
        var minPoint = new qq.maps.LatLng(minLat, minLng); // 创建点坐标B
        setZoom(maxPoint, minPoint, tmap, id);
    }
}

//自定义光标的方法
$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
$.fn.getCursorPosition = function () {
    var el = $(this).get(0);
    var pos = 0;
    if ('selectionStart' in el) {
        pos = el.selectionStart;
    } else if ('selection' in document) {
        el.focus();
        var Sel = document.selection.createRange();
        var SelLength = document.selection.createRange().text.length;
        Sel.moveStart('character', -el.value.length);
        pos = Sel.text.length - SelLength;
    }
    return pos;
}
